<?php
  // no direct access
  defined( '_JEXEC' ) or die( 'Restricted access' );
  jimport('joomla.application.component.controller');
  include("base.php");

  class TeamController extends BaseController
  {  
    var $_name = 'team';
    
    function edit(){
      
      $document =& JFactory::getDocument();
      $view = & $this->getView($this->_name, $document->getType());
      $view->setModel($this->getModel('pic','picmodel'));
      
      parent::edit();
    }
    
    function save()
    {
      $data = JRequest::get('POST');
      $data['description'] = JRequest::getVar( 'description', '', 'post', 'string', JREQUEST_ALLOWHTML );
       
      $mpic = $this->getModel('pic','picmodel');
      
      $pics = $this->reconstruct_pics($data);
	  foreach($pics as $k => $v){
        $tmp      = $mpic->save($v);
        $data[$k] = $tmp->id;
      }
      
      $model  = & $this->getModel($this->_name); 
      $season = $model->save($data);
      
      $redirectTo = JRoute::_('index.php?option='.JRequest::getVar('option').'&c='.JRequest::getVar('c'), false);
      $this->setRedirect($redirectTo,  ucfirst($this->_name) . ' Saved!');             
    }
    
    private function reconstruct_pics($data){
    
      $result = array();
      $result['pic_id']['id']          = $data['pic_id'];  
      $result['pic_id']['description'] = basename($data['pic_url']);
      $result['pic_id']['pic_type']    = 'TEAMS';
      $result['pic_id']['pic_id']      = $data['id'];
      $result['pic_id']['flickr_id']   = $data['pic_flickr_id'];
	  $result['pic_id']['url']         = $data['old_pic_url'];
      $result['pic_id']['pic_url']     = $data['pic_url'];
	  
	  if($result['pic_id']['id'])
        $result['pic_id']['updated_on'] = date('Y-m-d',time());
      else
        $result['pic_id']['created_on'] = date('Y-m-d',time());
	  
	  $result['logo_id']['id']          = $data['logo_pic_id'];  
      $result['logo_id']['description'] = basename($data['logo_pic_url']);
      $result['logo_id']['pic_type']    = 'TEAMS';
      $result['logo_id']['pic_id']      = $data['id'];
      $result['logo_id']['flickr_id']   = $data['logo_flickr_id'];
	  $result['logo_id']['url']         = $data['old_logo_pic_url'];
      $result['logo_id']['pic_url']     = $data['logo_pic_url'];
	  
	  if($result['logo_id']['id'])
        $result['logo_id']['updated_on'] = date('Y-m-d',time());
      else
        $result['logo_id']['created_on'] = date('Y-m-d',time());
      
      return $result;
    
    }
  }
?>